//
//  NDSchemeManager.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/27.
//


import SwiftUI

enum NDSchemeType: String {
    case main = "plattry"
    case login = "nesing"
    case order = "thirdard"
    case product = "mythling"
}

struct NDSchemeParams {
    let tab: String?
    let productId: Int?
    
    init(queryItems: [URLQueryItem]?) {
        var tabValue: String?
        var productIdValue: Int?
        
        queryItems?.forEach { item in
            if item.name == "lys" {
                tabValue = item.value
            } else if item.name == "exterior", let value = item.value {
                productIdValue = Int(value)
            }
        }
        
        self.tab = tabValue
        self.productId = productIdValue
    }
}

// 通知键值
struct NDSchemeKeys {
    static let tabIndex = "tabIndex"
    static let productId = "productId"
    static let orderTab = "orderTab"
}

class NDSchemeManager {
    static let shared = NDSchemeManager()
    
    private init() {}
    
    func handleURL(_ urlString: String) {
        guard let url = URL(string: urlString),
              let schemeType = NDSchemeType(rawValue: url.lastPathComponent) else {
            print("❌ 无效URL: \(urlString)")
            return
        }
        
        let params = NDSchemeParams(queryItems: URLComponents(string: urlString)?.queryItems)
        
        DispatchQueue.main.async {
            self.process(schemeType: schemeType, params: params)
        }
    }
    
    private func process(schemeType: NDSchemeType, params: NDSchemeParams) {
        print("📍 处理Scheme跳转: \(schemeType)")
        
        switch schemeType {
        case .main:
            // 跳转到首页并刷新
            NotificationCenter.default.post(
                name: .schemeSwitchTab,
                object: nil,
                userInfo: [NDSchemeKeys.tabIndex: 0]
            )
            NotificationCenter.default.post(name: .schemeRefreshHome, object: nil)
            
        case .login:
            // 显示登录页面
            NotificationCenter.default.post(name: .schemeShowLogin, object: nil)
            
        case .order:
            // 跳转到订单页，可带tab参数
            var userInfo: [String: Any] = [NDSchemeKeys.tabIndex: 1]
            if let tab = params.tab {
                userInfo[NDSchemeKeys.orderTab] = tab
            }
            NotificationCenter.default.post(
                name: .schemeSwitchTab,
                object: nil,
                userInfo: userInfo
            )
            
        case .product:
            // 显示产品详情
            if let productId = params.productId {
                NotificationCenter.default.post(
                    name: .schemeShowProductDetail,
                    object: nil,
                    userInfo: [NDSchemeKeys.productId: productId]
                )
            } else {
                print("❌ 产品ID为空")
            }
        }
    }
}
